﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using studentSubsidy.Entity;
using studentSubsidy.Entity.User;
using studentSubsidy.Models;
using studentSubsidy.Service;

namespace studentSubsidy.Controllers
{
    [ApiController]
    [Route("api/[Action]")]
    public class UserController: Controller
    {
        public TokenOptions TokenOptions { get; }

        private UserService _userService = new UserService();
        
        public UserController(IOptions<TokenOptions> options)
        {
            TokenOptions = options.Value;
        }

        [HttpPost(Name = "login")]
        public LoginResult Login([FromBody] UserLoginQuery userLoginQuery)
        {
            User user = _userService.userLogin(userLoginQuery);
            if (user!=null)
            {
                string token = new JwtUtils(TokenOptions).CreateTokenAsync(user.username,user.role);
                return new LoginResult(200, "Bearer " + token, "登录成功",user);
            }else
                return new LoginResult(400, "", "",null);
        }

        [HttpPost(Name = "register")]
        public Result Register([FromBody] RegisterQuery registerQuery)
        {
            _userService.userRegister(registerQuery);
            return new Result(200, "注册成功", registerQuery.Username,0);
        }
    }
}